﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Collections.ObjectModel;

namespace WpfApplication2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
       
        ObservableCollection<percentItem> downloadList = new ObservableCollection<percentItem> { };
        


        List<Task<int>> tasks = new List<Task<int>> { };
        private static int  max_item=3;
        private int started_task = 0;

        public MainWindow()
        {
            InitializeComponent();
            label_state.Content = "";
            inp_url.Clear();
            Binding bd = new Binding();
            bd.Source = downloadList;
            view.SetBinding(ListBox.ItemsSourceProperty, bd);
        }

        private async void add_btn_Click(object sender, RoutedEventArgs e)
        {
            if (downloadList.Count() <= started_task)
            {
                downloadList.Add(new percentItem(inp_url.Text, 0, 0));
                await Looper();
            }
            else 
            {
                downloadList.Add(new percentItem(inp_url.Text, 0, 0));           
            }
            //inp_url.Clear();
        }
        private async Task Looper() {
            label_state.Content = "running.";
            while (downloadList.Count() > started_task)
            {
                
                if (tasks.Count() < max_item)
                {
                    tasks.Add(progressurl(downloadList[downloadList.Count()-1]));
   

                }else
                {

                    started_task++;
                }

            }
            int[] total = await Task.WhenAll(tasks);
            label_state.Content="finish.total"+total.Sum().ToString();
            
        }
        private async Task<int> progressurl(percentItem item)
        {
            var result = new MemoryStream();
            var req = (HttpWebRequest)HttpWebRequest.Create(item.Name);
            var res =(HttpWebResponse) await req.GetResponseAsync();
            long length=res.ContentLength;
            item.Size = length;
            var stream=res.GetResponseStream();
            byte[] by = new byte[1024];
            long totaldownloadsize = 0;
            int osize = await stream.ReadAsync(by, 0, by.Length);
            while (osize > 0)
            {
                totaldownloadsize += osize;
                await result.WriteAsync(by,0,osize);
                item.Percent =(int)( (float)totaldownloadsize / (float)length * 100);
                osize = await stream.ReadAsync(by, 0, by.Length);
            }
            res.Close();
            result.Close();
            return (int)length;
        }

    }
}
